//
//  NetworkManager.swift
//  BaoKeSwift
//
//  Created by duan on 26/09/2017.
//  Copyright © 2017 geek-duan. All rights reserved.
//

import Foundation
import Alamofire


class BKNetworkManager {
    //单例
    static let shared = BKNetworkManager()
    /// - HTTP请求头
    let headers: HTTPHeaders = [
        "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Accept": "application/json"
    ]
    
//    // MARK: - 带sessid的数据请求
//    func sessionidRequset(method: HTTPMethod = .get, URLString: String, parameters: [String: Any]?, completion: @escaping (_ isSuccess: Bool, _ result: Any?, _ message: String) -> ()) {
//        
//        /// - 1.判断是否有sessionid值
//        guard let sessionid = UserAuthManager.shared.userM?.sessionId else {
//            /// - 进行没有sessionid的请求
//            Requset(method: method, URLString: URLString, parameters: parameters, completion: completion)
//            return
//        }
//        //2.判断parameters是否有值
//        var parameters = parameters
//        if parameters == nil {
//            //如果没有就进行实例化
//            parameters = [String: Any]()
//        }
//        //3.设置sessionid值:此时parameters一定不为nil，可以强转
//        parameters!["sessionId"] = sessionid as Any
//        
//        /// - 4.调用通用请求方法
//        Requset(method: method, URLString: URLString, parameters: parameters, completion: completion)
//    }
    
    // MARK: - 通用请求
    ///
    /// - Parameters:
    ///   - method: 请求方式
    ///   - URLString: 请求地址
    ///   - parameters: 请求参数
    ///   - completion: 回调数据内容
    func Requset(method: HTTPMethod = .get, URLString: String, parameters: [String: Any]?, completion: @escaping (_ isSuccess: Bool, _ result: Any?, _ message: String) -> ()) {
        
        Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default
            , headers: headers).responseJSON { (response) in
                
                response.result.ifSuccess({//--------------------成功
                    guard let JSONResult = response.result.value as? [String: Any] else {
                        return
                    }
                    /// - 获取后台数据库的相应提示信息
                    let message = JSONResult["message"] as? String ?? ""
                    
                    if JSONResult["code"] as? String == "100" {
                        /// - 回调数据 
                        completion(true, JSONResult["result"] as Any?, message)
                    } else {
                        /// - 回调提示信息
                        completion(false, nil, message)
                    }
                })
                
                response.result.ifFailure({ // -------------------------失败
                    
                    /// - 回调网络错误信息
                    completion(false, nil, "网络错误，请检查网络设置。")
                    
                    guard let error = response.result.error as NSError? else {
                        return
                    }
                    let errorInfo = error.userInfo["NSLocalizedDescription"]
                        as? String ?? ""
                    // FIXME: - 网络错误信息提示：上架前去掉！或做对应网络处理
                    print("网络错误信息：\(errorInfo)")
                })  
        }
    }
}
